package com.lyb.jedis;

import redis.clients.jedis.Jedis;

import java.util.Random;

/**
 * @author lyb
 * @create 2022/3/12-13:41
 * @method
 */
public class PhoneCode {

    public static void main(String[] args) {
        verifyCode("15713680087");
        // getRedisCode("15713680087", "372187");
    }

    // 生成6位验证码
    public static String getCode(){
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 6; i++) {
            int rand = random.nextInt(10);
            sb.append(rand);
        }
        return sb.toString();
    }

    // 每个手机每天只能发送3次验证码，放到redis中，并且设置过期时间
    public static void verifyCode(String phone){
        Jedis jedis = new Jedis("192.168.31.235", 6379);

        // 手机发送次数key
        String countKey = "VerifyCode" + phone + ":count";
        // 验证码key
        String codeKey = "VerifyCode" + phone + ":code";

        // 每个手机每天只能发送三次
        String count = jedis.get(countKey);
        if (count == null) {
            jedis.setex(countKey, 24 * 60 * 60, "1");
        }else if(Integer.parseInt(count) <= 2){
            jedis.incr(countKey);
        }else if(Integer.parseInt(count) > 2){
            System.out.println("今天您已经发送了3次，无法继续发送");
            jedis.close();
            return;
        }

        //发送验证码放到redis中
        String vCode = getCode();
        jedis.setex(codeKey, 120, vCode);
        jedis.close();

    }

    // 验证码校验
    public static void getRedisCode(String phone, String code){
        Jedis jedis = new Jedis("192.168.31.235", 6379);
        String codeKey = "VerifyCode" + phone + ":code";
        String redisCode = jedis.get(codeKey);
        if (redisCode.equals(code)){
            System.out.println("验证成功");
        }else {
            System.out.println("验证失败");
        }
        jedis.close();
    }
}
